package com.caiya.controller;

import com.caiya.config.FtpConfig;
import com.caiya.mapper.EmployeeMapper;
import com.caiya.dto.Photo;
import com.caiya.dto.User;
import com.caiya.util.FtpUtil;
import com.caiya.util.UploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/11/7 0007.
 */
@RestController
@RequestMapping("/user")
public class UserCartController {

//    @Autowired
//    private FtpConfig ftpConfig;

    @Autowired
    private EmployeeMapper employeeMapper;

    @GetMapping(value = "/list")
    public List<User> user(){
        List<User> list = employeeMapper.list();
        return list;
//        return null;
    }

    @PostMapping(value = "/upload")
    public  List<Photo> uploadFiles(@RequestParam("file")MultipartFile[] files) throws IOException {
        List<Photo> photoList = new ArrayList<Photo>();
        //循环上传多个图片
        for(MultipartFile file:files){
            Photo photo = new Photo();

            String oldName = file.getOriginalFilename();
            String picNewName = UploadUtils.generateRandonFileName(oldName);//通过工具类产生新图片名称，防止重名

            String picSavePath = UploadUtils.generateRandomDir(picNewName);//通过工具类把图片目录分级

//            photo.setPhotoUrl(picSavePath+"/"+picNewName);//设置图片的url--》就是存储到数据库的字符串url
            photo.setAlbumId(1);//设置图片所属相册id
            photo.setPhotoDesc(oldName);//设置图片描述



            FtpConfig ftpConfig = new FtpConfig();

            String s = FtpUtil.pictureUploadByConfig(ftpConfig, picNewName, picSavePath, file.getInputStream());//上传到图片服务器的操作
            photo.setPhotoUrl(s);
            photoList.add(photo);
        }

        //添加到数据库
//        iPhotoService.savePhotoList(photoList);//调用service层方法

        return photoList;//上传成功做的操作,我这里返回上传成功的信号
    }

}
